//
//  CAOrderListViewController.m
//  LNH
//
//  Created by twentylx on 2018/2/13.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAOrderListViewController.h"
#import "HTHorizontalSelectionList.h"
#import <MJRefresh/MJRefresh.h>
#import "CAOrderListTableViewCell.h"
#import "CAOrderListApi.h"
#import "CACancelOrderApi.h"
#import "CARemindOrderApi.h"
#import "CAConfirmApi.h"
#import "CAOrderDetailViewController.h"
#import "CAOrderDetailApi.h"

@interface CAOrderListViewController () <HTHorizontalSelectionListDataSource, HTHorizontalSelectionListDelegate, UITableViewDataSource, UITableViewDelegate> {
    NSInteger _page;
}


@property (nonatomic, strong) NSArray *selectionArray;
@property (nonatomic, strong) HTHorizontalSelectionList *selectionList;

@property (nonatomic, strong) NSMutableArray *orderArray;
@property (nonatomic, strong) UITableView *orderTableView;
@end

static NSString *CellIdentify = @"OrderCell";

@implementation CAOrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/// 初始化数据
- (void)lm_initialDefaultsForController {
    self.selectionArray = @[
                       @{@"name":@"全部",@"status":@""},
                       @{@"name":@"待付款",@"status":@"1"},
                       @{@"name":@"待发货",@"status":@"2"},
                       @{@"name":@"待收货",@"status":@"3"},
                       @{@"name":@"已完成",@"status":@"4"},
                       ];
}

/// 绑定 vm
- (void)lm_bindViewModelForController {
}

/// 创建视图
- (void)lm_createViewForController {
    [self.view setNeedsUpdateConstraints];
    
    [self.view addSubview:self.selectionList];
    [self.view addSubview:self.orderTableView];
}

/// 配置导航栏
- (void)lm_configNavigationForController {
    self.navigationItem.title = @"订单列表";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
    
    [self.selectionList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.and.right.equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    
    [self.orderTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.selectionList.mas_bottom);
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}

#pragma mark get & set
-(HTHorizontalSelectionList *) selectionList {
    if (!_selectionList) {
        _selectionList = [[HTHorizontalSelectionList alloc] initWithFrame:CGRectZero];
        [_selectionList setDelegate:self];
        [_selectionList setDataSource:self];
        //        [_selectionList setCenterButtons:YES];
        [_selectionList setBottomTrimHidden:YES];
        [_selectionList setBottomTrimColor:RGBCOLOR(41, 151, 236)];
        [_selectionList setSelectionIndicatorColor:RGBCOLOR(41, 151, 236)];
        [_selectionList setTitleColor:RGBCOLOR(153, 153, 153) forState:UIControlStateNormal];
        [_selectionList setTitleColor:RGBCOLOR(41, 151, 236) forState:UIControlStateSelected];
        _selectionList.centerButtons = YES;
        [_selectionList setSelectedButtonIndex:[self.status integerValue] animated:YES];
    }
    return _selectionList;
}

- (UITableView *) orderTableView {
    if (!_orderTableView) {
        _orderTableView = [UITableView new];
        _orderTableView.dataSource = self;
        _orderTableView.delegate = self;
        [_orderTableView setBackgroundColor: [UIColor whiteColor]];
        _orderTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_orderTableView registerClass:[CAOrderListTableViewCell class] forCellReuseIdentifier:CellIdentify];
        _orderTableView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
        [_orderTableView.mj_header beginRefreshing];
        _orderTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _orderTableView;
}

#pragma mark private method
- (void) backAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void) refreshData {
    _page = 1;
    [self loadDataWithStatus:_status Page:_page];
}

-(void) loadMoreData {
    _page++;
    [self loadDataWithStatus:_status Page:_page];
}

-(void)  loadDataWithStatus:(NSString *)status Page:(NSUInteger) page{
    
    CAOrderListApi *orderListApi = [[CAOrderListApi alloc] initWithPage:page Status:status];
    
    [orderListApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        CAOrderListApi *api = (CAOrderListApi *) request;
        NSLog(@"%@", api.responseObject[@"result"][@"data"]);
        if (page == 1 || self.orderArray == nil) {
            self.orderArray = [NSMutableArray arrayWithArray:api.responseObject[@"result"][@"data"]];
        } else {
            [self.orderArray addObjectsFromArray:api.responseObject[@"result"][@"data"]];
        }
        self.orderTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.orderTableView.bounds.size.width, 0.01f)];
        
        [self.orderTableView.mj_header endRefreshing];
        [self.orderTableView.mj_footer endRefreshing];
        [self.orderTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
        [self.orderTableView.mj_header endRefreshing];
        [self.orderTableView.mj_footer endRefreshing];
    }];
}

- (void) payAction {
    
}

- (void) cancelAction:(NSString *) orderId {
    CACancelOrderApi *cancelApi = [[CACancelOrderApi alloc] initWithOrderId:orderId];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [cancelApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CACancelOrderApi *api = (CACancelOrderApi *) request;
        if (api.done) {
            [SVProgressHUD lm_displaySuccessWithStatus:@"取消成功"];
            [self.orderTableView.mj_header beginRefreshing];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) remindOrderAction:(NSString *) orderId{
    CARemindOrderApi *remindOrderApi = [[CARemindOrderApi alloc] initWithOrderId:orderId];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [remindOrderApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CARemindOrderApi *api = (CARemindOrderApi *) request;
        if (api.done) {
            [SVProgressHUD lm_displaySuccessWithStatus:@"提醒成功"];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) confirmOrderAction:(NSString *) orderId {
    CAConfirmApi *confirmApi = [[CAConfirmApi alloc] initWithOrderId:orderId];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [confirmApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CAConfirmApi *api = (CAConfirmApi *) request;
        if (api.done) {
            [SVProgressHUD lm_displaySuccessWithStatus:@"收货成功"];
            [self.orderTableView.mj_header beginRefreshing];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) loadDetailWithOrderId:(NSString *)orderId {
    CAOrderDetailApi *orderDetailApi = [[CAOrderDetailApi alloc] initWithOrderId:orderId];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [orderDetailApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CAOrderDetailApi *api = (CAOrderDetailApi *) request;
        if (api.done) {
            CAOrderDetailViewController *detailVC = [CAOrderDetailViewController new];
            detailVC.orderDetailDict = api.responseObject[@"result"][@"order"];
            detailVC.goodsArray = api.responseObject[@"result"][@"order"][@"order_goods"];
            [self.navigationController pushViewController:detailVC animated:YES];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma mark HTSELECTIONLIST Delegate
- (NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList {
    return self.selectionArray.count;
}

- (NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index {
    NSDictionary *dict = self.selectionArray[index];
    return dict[@"name"];
}

- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index {
    NSDictionary *dict = self.selectionArray[index];
    self.status = dict[@"status"];
    [self.orderTableView.mj_header beginRefreshing];
}

#pragma mark UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _orderArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CAOrderListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify];
    NSDictionary *dict = _orderArray[indexPath.row];
    
     cell = [[CAOrderListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify];

    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell configureForCell:_orderArray[indexPath.row]];
//    cell.orderModel = _orderArray[indexPath.row];
    
    UITapGestureRecognizer *detailGesture = [UITapGestureRecognizer new];
    [cell.goodsView addGestureRecognizer:detailGesture];
    [[detailGesture rac_gestureSignal] subscribeNext:^(id x) {
        [self loadDetailWithOrderId:[NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]]];
    }];
    
    if ([dict[@"status"] integerValue] == 0) {
        cell.cell2Button.hidden = YES;
        cell.cell1Button.hidden = YES;
    } else if ([dict[@"status"] integerValue] == 1) {
        [cell.cell2Button setTitle:@"支付" forState:UIControlStateNormal];
        [[[cell.cell2Button rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
//            [self confirmOrderAction:[NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]]];
        }];
        cell.cell1Button.hidden = NO;
        [cell.cell1Button setTitle:@"取消订单" forState:UIControlStateNormal];
        [[[cell.cell1Button rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self cancelAction:[NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]]];
        }];
    } else if ([dict[@"status"] integerValue] == 2) {
        [cell.cell2Button setTitle:@"提醒发货" forState:UIControlStateNormal];
        [[[cell.cell2Button rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self remindOrderAction:[NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]]];
        }];
        cell.cell1Button.hidden = YES;
    } else if ([dict[@"status"] integerValue] == 3) {
        [cell.cell2Button setTitle:@"确认收货" forState:UIControlStateNormal];
        [[[cell.cell2Button rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self confirmOrderAction:[NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]]];
        }];
        cell.cell1Button.hidden = NO;
        [cell.cell1Button setTitle:@"查看物流" forState:UIControlStateNormal];
        [[[cell.cell1Button rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
//            [self cancelAction:[NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]]];
        }];
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *goodsArray  = _orderArray[indexPath.row][@"order_goods"];
    float height = goodsArray.count * 120 + 150;
    return height;
}

@end
